<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Teacher extends Model
{
    protected $fillable = ['tc_code', 'name', 'is_logistics', 'phone'];

    public function levels(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(LevelTeacher::class, 'teachers_relate_level','tc_code','tl_code','tc_code','tl_code');
    }

    public function classes(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Classes::class, 'tc_code', 'tc_code');
    }

    public static function selectQuery($data): \Closure
    {
        return function ($query) use ($data) {
            if(!empty($data['tc_code'])){
                $query->where('tc_code', $data['tc_code']);
            }
            if(!empty($data['name'])){
                $query->where('name','like','%'.$data['name'].'%');
            }
        };
    }

    public static function add($data)
    {
        DB::beginTransaction();
        try {
            $teacherModel = Teacher::create($data);
            if (!$teacherModel) {
                throw new \Exception('');
            }
            //头衔
            if (!empty($data['tl_code'])) {
                $level = LevelTeacher::whereIn('tl_code',$data['tl_code'])->get();
                $teacherModel->levels()->attach($level);
            }
            //增加账号
            $adminData = [
                'username'=> $data['name'],
                'password' => bcrypt($data['phone']),
                'nickname' => $data['name'],
                'tc_code'=> $data['tc_code'],
                'status' => 1,
                'roles' => ['3']
            ];
            Admin::add($adminData);
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            return false;
        }
    }

    public function edit($data)
    {
        DB::beginTransaction();
        try {
            if (!$this) {
                throw new \Exception('');
            }
            $teacherModel = $this->update($data);
            if (!$teacherModel) {
                throw new \Exception('');
            }
            if (!empty($data['tl_code'])) {
                $level = LevelTeacher::whereIn('tl_code',$data['tl_code'])->get();
                $this->levels()->sync($level);
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            return false;
        }
    }
}
